package com.changcheng.project.yuminsi.commons;

import com.alibaba.fastjson.JSON;
import com.changcheng.project.handsetinfo.domain.AHandsetInfo;
import com.changcheng.project.handsetinfo.vo.HandSetRequest;
import com.changcheng.project.yuminsi.utils.GenerateSignUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.sound.midi.Soundbank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuminsi
 * @description
 * @date 2020/8/20 17:07
 * @since
 */
@SuppressWarnings("all")
@Component
public class RestTemplateHandheld {
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateHandheld.class);

    @Autowired
    private RestTemplate restTemplate;

    private static String appkey = "9065275281";
    private static String secretkey = "2b673290caa2d9a82f1f7e845c80e4fe";

    public String getResult(List<HandSetRequest> handSetRequests) throws Exception {
        //HTTP请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(mediaType);
        //签名验签
        headers.set("bt-auth-appkey", appkey);
        String nonce = RandomStringUtils.randomAlphanumeric(16).toLowerCase();
        headers.set("bt-auth-nonce", nonce);
        String timestamp = String.valueOf(System.currentTimeMillis());
        headers.set("bt-auth-timestamp", timestamp);

        //访问第三方路径
        String url = "https://gw-third-system-sit.beantechyun.cn/third-system-service/device-master/etc/syncETCHandSet";
        String uri = "/".concat(url.substring(url.indexOf("third-system-service"), url.length()));
        logger.info("uri: {}", uri);

        //参数
        //对象转json
        String handsetInfo = JSON.toJSONString(handSetRequests);
        Map<String, Object> postBody = new HashMap<>();
        postBody.put("json", handsetInfo);
        String genSign = GenerateSignUtil.generateSignOfPost(uri, appkey, nonce, timestamp, postBody, secretkey);
        headers.set("bt-auth-sign", genSign);
        logger.info("POST生成的签名:  {}", genSign);


        HttpEntity<String> entity = new HttpEntity<>(handsetInfo, headers);


        //调用第三方接口
        String str = restTemplate.postForObject(url, entity, String.class);
        logger.info("resultStr: {}", str);
        return str;
    }
}
